//
//  KKAdviceChatVC.m
//  DoMi
//
//  Created by 康凯 on 2016/12/6.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKAdviceChatVC.h"
#import "KKChatCell.h"
#import "KKChatM.h"
#import "KKVoiceView.h"
#import "KKAudioRecorder.h"
#import "KKUploadUtils.h"
#import "KKComHttp.h"
#import "KKAdviceDetailM.h"
#import "KKAdviceCommentVC.h"
#import "KKChatSendTextVC.h"
#import "KKPayDialog.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import "KKPayInfoM.h"
#define ALIPAY_SCHEMA @"KKDoMiAlipay"
#import "KKChatNoPayDialog.h"

@interface KKAdviceChatVC ()<UITableViewDelegate,UITableViewDataSource,KKRecorderEventDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet UITextField *inputContent;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputBottom;
@property (strong,nonatomic)NSTimer *timer;
@property (strong,nonatomic)KKVoiceView *recorderView;
@property(nonatomic,strong)KKAudioRecorder *recorder;

@property (strong, nonatomic) KKUploadUtils *uploadUtils;
@property (weak, nonatomic) IBOutlet UIView *adviceSuccessView;
@property (copy,nonatomic)NSString *askType;
@property (copy,nonatomic)NSString *questionContent;
@property (strong,nonatomic)KKAdviceDetailM *chatInfo;
@property (strong,nonatomic)NSArray *chatDatas;
@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (copy,nonatomic)NSString *payType;
@property (weak, nonatomic) IBOutlet UILabel *expertName1;
@property (weak, nonatomic) IBOutlet UILabel *company1;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UILabel *publishTime;
@end

@implementation KKAdviceChatVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
    [self setNavWhite];
    [self registerForKeyboardNotifications];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.inputContent.textColor=[UIColor blueColor];
    if(self.flag==0){
        self.tableView.hidden=YES;
        self.expertName1.text=self.expertName;
//        self.company1.text=self.expertCompany;
        self.company1.text=@"专家";
    }else{
        self.inputView.hidden=YES;
        self.commentView.hidden=NO;
    }
    self.inputContent.delegate=self;
    
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView registerClass:[KKChatCell class] forCellReuseIdentifier:@"KKChatCell"];
    if(self.chatDatas!=nil&&self.chatDatas.count!=0){
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatDatas.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [self.backView addGestureRecognizer:tap];
    
    //支付成功回调
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(wXPayNotice:) name:@"wxPaySuccess" object:nil];
    
    __weak typeof(self) weakSelf=self;
    self.recorder=[[KKAudioRecorder alloc]init];
    self.recorder.recorderSuccessBlock=^(NSURL *url){
        
        KKLog(@"localUrl--->%@",url.path);
        //创建文件管理器
        /*NSFileManager可以用来查询单词库目录，创建，重命名，删除目录以及获取／设置文件属性的方法*/
        NSFileManager * fm;
        fm = [NSFileManager defaultManager];
        //创建缓冲区，利用NSFileManager对象来获取文件中的内容，也就是这个文件的属性可修改
        NSData * fileData;
        fileData = [fm contentsAtPath:url.path];

        [weakSelf.uploadUtils uploadRecorderAudio:fileData];

    };
    
    //录制语音界面
    KKVoiceView *voice=[[[NSBundle mainBundle] loadNibNamed:@"KKVoiceView" owner:self options:nil] lastObject];
    self.recorderView=voice;
    self.recorderView.delegate=self;
    CGRect temp= voice.frame;
    temp.origin.y=screenHeight-201;
    voice.frame=temp;
    //上传语音
    self.uploadUtils=[[KKUploadUtils alloc] init];
    self.uploadUtils.uploadBlock=^(NSString *url){
        KKLog(@"url---->%@",url);
        weakSelf.questionContent=url;
        [weakSelf adviceToExpert];
    };
    if(![KKAppUtils isEmptyString:self.consultId]){
        [self getAdviceChatList];
    }
}
#pragma mark textfield代理
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [self.view endEditing:YES];
    KKChatSendTextVC *send=[[KKChatSendTextVC alloc] init];
    send.expertId=self.expertId;
    send.expertName=self.expertName;
    send.expertCompany=self.expertCompany;
    send.sendSuccessBlock=^(){
        self.inputView.hidden=YES;
        self.adviceSuccessView.hidden=NO;
        self.publishTime.hidden=NO;
        self.publishTime.text=[KKAppUtils getCurrentTime:@"YYYY年MM月dd日 hh:mm:ss"];
    };
    [self.navigationController pushViewController:send animated:YES];
}
#pragma mark tableview代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatDatas.count+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KKChatCell *cell=[tableView dequeueReusableCellWithIdentifier:@"KKChatCell"];
    if(indexPath.row>0){
        [cell refreshCell:self.chatDatas[indexPath.row-1] index:indexPath.row];
    }else{
        cell.adviceFirst=self.chatInfo;
        [cell refreshCell:self.chatDatas[indexPath.row] index:indexPath.row];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        if([self.chatInfo.asktype isEqualToString:@"1"]){
            return 50+45;
        }else{
            CGRect rec =  [self.chatInfo.question boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
            return rec.size.height + 45;
        }
    }else{
        KKChatM *model = self.chatDatas[indexPath.row-1];
        if([model.contenttype isEqualToString:@"1"]){
            return 50+45;
        }else{
            CGRect rec =  [model.content boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
            return rec.size.height + 45;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        if([self.chatInfo.asktype isEqualToString:@"1"]){
            [self.recorder playAudio:self.chatInfo.question];
        }
    }else{
        [self playRecorder];
        KKChatM *model = self.chatDatas[indexPath.row-1];
        if([self.chatInfo.payflag isEqualToString:@"0"]){
            KKPayDialog *pay=[[[NSBundle mainBundle] loadNibNamed:@"KKPayDialog" owner:self options:nil] lastObject];
            pay.payTypeBlock=^(NSString *type){
                self.payType=type;
                [self advicePay];
            };
            [pay show];
        }else{
            if([model.contenttype isEqualToString:@"1"]){
                [self.recorder playAudio:model.content];
            }
        }
        
    }
}
#pragma mark 通知接受
-(void)wXPayNotice:(NSNotificationCenter *)center{
    [self toast:@"支付成功成功"];
    [self getAdviceChatList];
}
#pragma mark 按钮--发送文字
- (IBAction)sendClick:(id)sender {
    if([KKAppUtils isEmptyString:self.inputContent.text]){
        [self toast:@"请输入咨询内容"];
        return;
    }
    self.askType=@"0";
    [self.view endEditing:YES];
    if(self.flag==0){
        self.inputView.hidden=YES;
        self.questionContent=self.inputContent.text;
        [self adviceToExpert];
    }else{

        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatDatas.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}
#pragma mark 按钮--返回
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 按钮--发送语音
- (IBAction)voiceClick:(id)sender {
    self.askType=@"1";
    [self.view endEditing:YES];
    for (UIView *subView in self.view.subviews) {
        if([subView isKindOfClass:[KKVoiceView class]]){
            [subView removeFromSuperview];
            self.inputBottom.constant=0;
        }else{
            [self.view addSubview:self.recorderView];
            self.inputBottom.constant=201;
        }
    }

}
#pragma mark 按钮--点击评论
- (IBAction)commentClick:(id)sender {
    if([self.chatInfo.payflag isEqualToString:@"1"]){
        KKAdviceCommentVC *comment=[[KKAdviceCommentVC alloc] init];
        comment.consultId=self.consultId;
        [self.navigationController pushViewController:comment animated:YES];
    }else{
        KKChatNoPayDialog *noPay=[[[NSBundle mainBundle] loadNibNamed:@"KKChatNoPayDialog" owner:self options:nil] lastObject];
        [noPay show];
    }
    
}

#pragma mark voice代理
-(void)recorderTouchUp{
    [self.recorder openRecorder];
    self.timer=[NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        self.recorderView.time+=0.1;
        [self.recorderView setTime];
        self.recorderView.shapeLayer.strokeEnd+=0.001;
    }];
}
-(void)recorderTouchInside{
    self.recorderView.shapeLayer.strokeEnd=0;
    self.inputView.hidden=YES;
    for (UIView *subView in self.view.subviews) {
        if([subView isKindOfClass:[KKVoiceView class]]){
            [subView removeFromSuperview];
            self.inputBottom.constant=0;
        }
    }
    [self.recorder stopRecorder:NO];
    [self.timer invalidate];
}
-(void)recorderTouchMove{
    
}

#pragma mark 接口--咨询专家
-(void)adviceToExpert{
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"asktype":self.askType,@"question":self.questionContent,@"expertid":self.expertId};
    [KKComHttp adviceToExpert:params success:^(id data) {
        self.adviceSuccessView.hidden=NO;
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 接口--咨询列表
-(void)getAdviceChatList{
    [self showDialog];
    [KKComHttp getAdviceDetail:self.consultId success:^(id data) {
        NSArray *chat=data;
        self.chatInfo=chat[0];
        if(self.flag==1){
            if([KKAppUtils isEmptyString:self.chatInfo.realname]){
                self.expertName1.text=@"匿名";
            }else{
                self.expertName1.text=self.chatInfo.realname;
            }
            self.company1.text=@"专家";
        }
        if(self.chatInfo.users!=nil&&self.chatInfo.users.count>0){
            self.chatDatas=self.chatInfo.users;
            self.commentView.hidden=NO;
        }else{
            self.commentView.hidden=YES;
        }
        [self.tableView reloadData];
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}
#pragma mark 接口--咨询支付
-(void)advicePay{
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"consultid":self.chatInfo.consultid,@"paytype":self.payType};
    [KKComHttp advicePay:params success:^(id data) {
        if([self.payType isEqualToString:@"wx"]){
            KKPayInfoM *payInfo=[KKPayInfoM mj_objectWithKeyValues:data];
            //调起微信支付
            PayReq* req = [[PayReq alloc] init];
            req.partnerId = payInfo.partnerid;
            req.prepayId = payInfo.prepayid;
            req.nonceStr = payInfo.noncestr;
            req.timeStamp = payInfo.timestamp.intValue;
            req.package = payInfo.package;
            req.sign = payInfo.sign;
            [WXApi sendReq:req];
        }else{
            // 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:data fromScheme:ALIPAY_SCHEMA callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut ====== %@",resultDic);
            }];
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 接口--听语音
-(void)playRecorder{
    [KKComHttp playRecorder:self.consultId success:^(id data) {
        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - keyboardHight
- (void)registerForKeyboardNotifications
{
    //监听键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardDidShowNotification object:nil];
    //监听键盘隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden) name:UIKeyboardWillHideNotification object:nil];
    
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    //获取键盘高度
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.inputBottom.constant=kbSize.height;

    if (self.chatDatas.count != 0)
    {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatDatas.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

//当键盘隐藏的时候
- (void)keyboardHidden
{
    self.inputBottom.constant=0;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}



@end
